package Component;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;


import javax.swing.JPanel;

import Main.Game;

public class Board extends JPanel implements Runnable {

	private Game game;
	private Thread animator;
	public final int[] DELAY = new int[]{60,40,25};
	//public final int DELAY = 40;

	public Board() {
		addKeyListener(new TAdapter());
		addMouseListener(new CAdapter());
		addMouseMotionListener(new MAdapter());
		setFocusable(true);
		setBackground(Color.BLACK);
		setDoubleBuffered(true);
		game = new Game(getWidth(), getHeight());
	}

	@Override
	public void addNotify() {
		super.addNotify();
		animator = new Thread(this);
		animator.start();
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		Graphics2D g2d = (Graphics2D) g;

		game.draw(g2d);

		g.dispose();
	}

	public void update() {

		game.setSize(getWidth(), getHeight());
		game.update(0);
                if(game.isExit ==true)
                {
                    System.exit(0);
                }
	}

	@Override
	public void run() {

		long beforeTime, timeDiff, sleep;
		/*try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			System.out.println("interrupted");
		}
		ResourceManager.getRes();*/
/*		game.setSize(getWidth(), getHeight());
		game.gameState = new MenuState(game);*/


		beforeTime = System.currentTimeMillis();
		while (true) {


			update();
			repaint();

			timeDiff = System.currentTimeMillis() - beforeTime;
			sleep = DELAY[Global.GlobalGameOption.getOption().speed] - timeDiff;

			if (sleep < 0) {
				sleep = 2;
			}
			try {
				Thread.sleep(sleep);
			} catch (InterruptedException e) {
				System.out.println("interrupted");
			}
			beforeTime = System.currentTimeMillis();
		}
	}

	private class MAdapter extends MouseMotionAdapter {

		@Override
		public void mouseDragged(MouseEvent e) {
			game.mouseDragged(e);
		}

		@Override
		public void mouseMoved(MouseEvent e) {

			game.mouseMoved(e);

		}
	}

	private class CAdapter extends MouseAdapter {

		@Override
		public void mousePressed(MouseEvent e) {
			game.mousePressed(e);
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			game.mouseReleased(e);
		}
	}

	private class TAdapter extends KeyAdapter {

		@Override
		public void keyReleased(KeyEvent e) {
			game.keyReleased(e);
		}

		@Override
		public void keyPressed(KeyEvent e) {
			game.keyPressed(e);
		}
	}
}